<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

/**
 * 测试接口
 * Class TestController
 * @package App\Http\Controllers\Api
 */
class TestController extends BaseController
{

    /**
     * 测试方法 - 勿删
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $params = $request->all();
        $method = getVal($params, 'm', 'hello');
        if ($method !== 'index') {
            if (!method_exists(self::class, $method)) {
                return $this->errorReturn('Method not found', 4005);
            }
            return $this->$method($request);
        }
        return $this->apiReturn();
    }

    /**
     * hello world
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function hello(Request $request)
    {
        $params = $request->all();
        return $this->apiReturn($params, 'hello world');
    }

    /**
     * get cache
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCache(Request $request)
    {
        $params = $request->all();
        $cacheKey = getVal($params, 'key');
        $driver = getVal($params, 'driver', 'redis');
        if (empty($cacheKey)) {
            return $this->errorReturn('empty key');
        }
        $res = Cache::store($driver)->get($cacheKey);
        return $this->apiReturn(['key' => $cacheKey, 'val' => $res]);
    }

    /**
     * set cache
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setCache(Request $request)
    {
        $params = $request->all();
        $cacheKey = getVal($params, 'key');
        $value = getVal($params, 'val');
        $minutes = getVal($params, 'ttl', 1 * 60 * 24);
        $driver = getVal($params, 'driver', 'redis');
        if (empty($cacheKey)) {
            return $this->errorReturn('empty key');
        }
        Cache::store($driver)->put($cacheKey, $value, $minutes);
        $res = Cache::store($driver)->get($cacheKey);
        return $this->apiReturn(['key' => $cacheKey, 'val' => $res]);
    }

    /**
     * delete cache
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delCache(Request $request)
    {
        $params = $request->all();
        $cacheKey = getVal($params, 'key');
        $driver = getVal($params, 'driver', 'redis');
        if (empty($cacheKey)) {
            return $this->errorReturn('empty key');
        }
        $res = Cache::store($driver)->forget($cacheKey);
        return $this->apiReturn(['key' => $cacheKey, 'val' => $res]);
    }

}